#import "ZNetManager.h"
#import <AFNetworking.h>
#define ZWDJ_Accept_key @"Accept"
#define ZWDJ_Author_Key @"x-wesports-token"
#import "NSString+Hash.h"
@implementation ZNetManagerHandler
+ (NSDictionary *)getParam:(NSDictionary *)parameters manager:(AFHTTPSessionManager *)manager{
    if (manager == nil) {
        return NULL;
    }
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
    NSMutableDictionary *parater  ;
    if (parameters) {
        parater = [[NSMutableDictionary alloc]initWithDictionary:parameters];
    }else
    {
        parater = @{}.mutableCopy;
    }
    NSInteger date = [[NSDate date] timeIntervalSince1970];
    NSString *dateString = @(date).stringValue;
    parater[@"timestamp"] = dateString;
    parater[@"nonce"] = [[dateString md5String] substringWithRange:NSMakeRange(0, 6)];
    ZWLog(@"parater %@",parater);
    NSArray *keyAarray = [parater allKeys];
    NSArray *sortArray = [keyAarray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:(NSNumericSearch)];
    }];
    NSMutableString *mutbleStr = [NSMutableString string];
    for (int i = 0;  i < sortArray.count; i++) {
        NSString *key = sortArray[i];
        NSString *value = parater[key];
        if (i == sortArray.count - 1) {
             [mutbleStr appendFormat:@"%@=%@",key,value];
        }else
        {
            [mutbleStr appendFormat:@"%@=%@&",key,value];
        }
       
    }
    [mutbleStr appendFormat:ZWDJ_Salt];
    NSString *sign = [[mutbleStr md5String] uppercaseString];
    parater[@"sign"] = sign;
    ZWLog(@"sign  %@",mutbleStr);
    return [parater copy];
}
@end

@implementation ZNetManager

static AFHTTPSessionManager *manager;
+ (AFHTTPSessionManager *)httpManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
    });
    return manager;
}
+ (NSURLSessionDataTask *)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError *))failure
{
    AFHTTPSessionManager *manager = [self httpManager];
    NSDictionary *parameter = [ZNetManagerHandler getParam:parameters manager:manager];
    return [manager GET:URLString parameters:parameter progress:nil success:success failure:failure];
  
}
+ (NSURLSessionDataTask *)PUT:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError *))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    NSDictionary *parater  = [ZNetManagerHandler getParam:parameters manager:manager];
    return [manager PUT:URLString parameters:parameters success:success failure:failure];
}

+ (NSURLSessionDataTask *)POST:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError *))failure
{
    AFHTTPSessionManager *manager = [self httpManager];
    NSDictionary *parameter = [ZNetManagerHandler getParam:parameters manager:manager];
    return [manager POST:URLString parameters:parameter progress:nil success:success failure:failure];
}

+ (NSURLSessionDataTask *)DELETE:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError *))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *parater  = [ZNetManagerHandler getParam:parameters manager:manager];
    return [manager DELETE:URLString parameters:parater success:success failure:failure];
}

+ (NSURLSessionDataTask *)POSTMessage:(NSString *)URLString images:(NSArray *)images parameters:(id)parameters progress:(void (^)(NSProgress *))uploadProgress success:(void (^)(NSURLSessionDataTask *, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError *))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    //    manager.requestSerializer.timeoutInterval = 15.0;
    NSString *api_token = @"";
    
    if (api_token) {
        api_token = [NSString stringWithFormat:@"Bearer %@",api_token];
        [manager.requestSerializer setValue:api_token forHTTPHeaderField:ZWDJ_Author_Key];
    }else
    {
        //        api_token = [NSString stringWithFormat:@"Bearer %@",@""];
    }
    //    NSString *apiTokenStr = [NSString stringWithFormat:@"Bearer %@",[UserModel currentUser].api_token];
    
    [manager.requestSerializer setValue:ZWDJ_Accept forHTTPHeaderField:ZWDJ_Accept_key];
    NSMutableDictionary *parater  ;
    if (parameters) {
        parater = [[NSMutableDictionary alloc]initWithDictionary:parameters];
        
    }else
    {
        parater = @{}.mutableCopy;
    }
    NSInteger date = [[NSDate date] timeIntervalSince1970];
    NSString *dateString = @(date).stringValue;
    parater[@"timestamp"] = dateString;
    parater[@"rand_string"] = [[dateString md5String] substringWithRange:NSMakeRange(0, 6)];
    ZWLog(@"parater %@",parater);
    NSArray *keyAarray = [parater allKeys];
    NSArray *sortArray = [keyAarray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:(NSNumericSearch)];
    }];
    NSMutableString *mutbleStr = [NSMutableString string];
    for (int i = 0;  i < sortArray.count; i++) {
        NSString *key = sortArray[i];
        NSString *value = parater[key];
        [mutbleStr appendFormat:@"%@=%@&",key,value];
    }
    [mutbleStr appendFormat:@"salt=%@%@",ZWDJ_Salt,parater[@"rand_string"]];
    NSString *sign = [mutbleStr md5String];
    parater[@"sign"] = sign;
    ZWLog(@"sign  %@",mutbleStr);
    NSDictionary *parameter = [parater copy];
    
    return [manager POST:URLString parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:uploadProgress success:success failure:failure];
    
}
+ (NSURLSessionDataTask *)PostCreatGroupInfo:(NSString *)urlStr param:(id)param image:(NSData *)imageData compleHandler:(void (^)(id _Nullable, NSError * _Nullable))compleHandler
{
    AFHTTPSessionManager *mgr =   [AFHTTPSessionManager manager];
    NSDictionary *parater = [ZNetManagerHandler getParam:param manager:mgr];
    
    return  [mgr POST:urlStr parameters:parater constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"logo" fileName:@"image.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        CGFloat completed = uploadProgress.completedUnitCount;
        CGFloat total = uploadProgress.totalUnitCount;
        CGFloat progress = completed/total;
        [ZProgressManager showProgress:progress];
        
        ZWLog(@"total %lld current %lld",uploadProgress.totalUnitCount,uploadProgress.completedUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        [ZProgressManager dismiss];
        NSNumber *code = responseObject[@"code"];
        
        compleHandler(responseObject,nil);
      
        if (code.integerValue != 200) {
            [ZProgressManager showInfo:responseObject[@"msg"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        ZWLog(@"error = %@",[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]);
        compleHandler(nil,error);
        [ZProgressManager dismiss];
        [ZProgressManager showInfo:@"服务器已断开"];
//        NSHTTPURLResponse *respone = error.userInfo[@"com.alamofire.serialization.response.error.response"];
        
    }];
    
}

@end
